package com.siqi.hr.common.redis;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import redis.clients.jedis.Jedis;

/**
 * Redis操作接口(注意redis默认会开启16个数据库，而这里我只配置了8个数据库风别是[0,1,2,3,4,5,6,7]redis默认使用第一个数据库0)
 * @author jinlong
 */
public class RedisAPI{
	static Logger log = LoggerFactory.getLogger(RedisAPI.class);
	
	public static void main(String[] args) {
		flushAll(0);
	}
	
    /**
     * 获取数据
     * @param key
     * @return
     */
    public static String get(String key,int dbId){
        //获取redis连接
    	Jedis jedis = RedisPoolManager.createInstance();
        //选择数据库
    	jedis.select(dbId);
        String value = null;
        try {
            value = jedis.get(key);
        } catch (Exception e) {
            //释放redis对象
        	RedisPoolManager.returnResource(jedis);
            log.error("Error",e);
        } finally {
            //返还到连接池
        	RedisPoolManager.returnResource(jedis);
        }
        return value;
    }
    
    /**
     * 向Redis里插入数据
     * @param key			key
     * @param second		过期时间
     * @param content		值
     * @return
     */
    public static String setKeyValue(String key,int second,String content,int dbId){
    	Jedis jedis = RedisPoolManager.createInstance();
    	jedis.select(dbId);
        String value = null;
        try {
            value = jedis.setex(key.getBytes(), second, content.getBytes());
        } catch (Exception e) {
        	RedisPoolManager.returnResource(jedis);
            log.error("Error",e);
        } finally {
            //返还到连接池
        	RedisPoolManager.returnResource(jedis);
        }
        return value;
    }
    
    
    /**
     * 向Redis里插入数据
     * @param key			key
     * @param content		值
     * @return            无过期时间
     */
    public static String setKeyValue(String key,String content,int dbId){
    	Jedis jedis = RedisPoolManager.createInstance();
    	jedis.select(dbId);
        String value = null;
        try {
            value = jedis.set(key, content);
        } catch (Exception e) {
        	RedisPoolManager.returnResource(jedis);
            log.error("Error",e);
        } finally {
            //返还到连接池
        	RedisPoolManager.returnResource(jedis);
        }
        return value;
    }

    /**
     * 向Redis里插入自定义对象
     * @param key			key
     * @param obj		    自定义对象
     * @return            无过期时间
     */
    public static String setKeyObject(String key,Object obj,int dbId){
        Jedis jedis = RedisPoolManager.createInstance();
        jedis.select(dbId);
        String setObjectRet = null;
        ByteArrayOutputStream bos =  new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            byte[] byteArray = bos.toByteArray();
            setObjectRet = jedis.set(key.getBytes(), byteArray);
        } catch (IOException e) {
            RedisPoolManager.returnResource(jedis);
            log.error("Error",e);
        }finally {
            try {
                //返还到连接池
                RedisPoolManager.returnResource(jedis);
                oos.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return setObjectRet;
    }

    /**
     * 向Redis里插入自定义对象
     * @param key			key
     * @return            无过期时间
     */
    public static Object getKeyObject(String key,int dbId){
        Jedis jedis = RedisPoolManager.createInstance();
        jedis.select(dbId);
        Object readObject = null;
        if(existsKey(key,dbId)){
            byte[] bs = jedis.get(key.getBytes());
            ByteArrayInputStream bis =  new ByteArrayInputStream(bs);
            ObjectInputStream inputStream = null;
            try {
                inputStream = new ObjectInputStream(bis);
                readObject = inputStream.readObject();
            } catch (IOException e) {
                RedisPoolManager.returnResource(jedis);
                log.error("Error",e);
            }catch (ClassNotFoundException e) {
                RedisPoolManager.returnResource(jedis);
                log.error("Error",e);
            }finally {
                try {
                    RedisPoolManager.returnResource(jedis);
                    inputStream.close();
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return readObject;
    }

    /**
     * 判断Key是否存在
     * @param key
     * @return    true key已经存在，false key不存在
     */
    public static boolean existsKey(String key,int dbId){
    	//log.debug("判断Key值是否存在，Key值为："+key);
    	Jedis jedis = RedisPoolManager.createInstance();
    	jedis.select(dbId);
        boolean bol = false;
        try {
            bol = jedis.exists(key);
        } catch (Exception e) {
        	RedisPoolManager.returnResource(jedis);
            log.error("Error",e);
        } finally {
            //返还到连接池
        	RedisPoolManager.returnResource(jedis);
        }
        return bol;
    }
    
    
    /**
     * 删除Redis指定的key值
     * @param key			key
     */
    public static void delKey(String key,int dbId){
    	Jedis jedis = RedisPoolManager.createInstance();
    	jedis.select(dbId);
        try {
        	if(existsKey(key,dbId)){
        		jedis.del(key);
        	}
        } catch (Exception e) {
            log.error("Error",e);
        } finally {
            //返还到连接池
        	RedisPoolManager.returnResource(jedis);
        }
    }
    
    /**
     * 获取Redis下面所有Key
     */
    public static void getKeys(int dbId){
    	Jedis jedis = RedisPoolManager.createInstance();
    	jedis.select(dbId);
         try {
             Set<String> keys = jedis.keys("*"); 
             Iterator<String> it=keys.iterator() ;   
             while(it.hasNext()){   
                 String key = it.next();   
             }
         } catch (Exception e) {
             //释放redis对象
        	 RedisPoolManager.returnResource(jedis);
             log.error("Error",e);
         } finally {
             //返还到连接池
        	 RedisPoolManager.returnResource(jedis);
         }
    }
    
    /**
     * 删除所有Key
     */
    public static void flushAll(int dbId){
    	Jedis jedis = RedisPoolManager.createInstance();
    	jedis.select(dbId);
    	 log.debug("清空所有的Key值");
         try {
             jedis.flushAll();		//清除所有数据库下的所有Key		flushdb删除当前选中的数据库中的所有Key
         } catch (Exception e) {
             //释放redis对象
        	 RedisPoolManager.returnResource(jedis);
             log.error("Error",e);
         } finally {
             //返还到连接池
        	 RedisPoolManager.returnResource(jedis);
         }
    }
    
    /**
     * 进队列
     * @param key
     * @param value
     */
    public static void push(String key, String value,int dbId) {
    	Jedis jedis = null;
    	try {
    		jedis = RedisPoolManager.createInstance();
    		jedis.select(dbId);			//使用1库做redis队列
    		jedis.lpush(key, value);
		} catch (Exception e) {
			RedisPoolManager.returnResource(jedis);
			log.error("ERROR",e);
		}finally {
			RedisPoolManager.returnResource(jedis);
		}
    }
 
    /**
     * 出队列
     * @param key	
     * @return 	返回数据库JSON字符串
     */
    public static String pop(String key,int dbId) {
    	String str = "";
    	Jedis jedis = null;
    	try {
    		jedis = RedisPoolManager.createInstance();
    		jedis.select(dbId);
    		str =  jedis.rpop(key);
		} catch (Exception e) {
			RedisPoolManager.returnResource(jedis);
			log.error("ERROR",e);
		}finally {
			RedisPoolManager.returnResource(jedis);
		}
        return str;
    }

    /**
     * 队列值
     * @param key
     * @return		返回队列长度
     */
    public static long count(String key,int dbId){
    	long lo = 0L;
    	Jedis jedis = null;
    	try {
    		jedis = RedisPoolManager.createInstance();
    		jedis.select(dbId);
			lo = jedis.llen(key);
		} catch (Exception e) {
			RedisPoolManager.returnResource(jedis);
			log.error("ERROR",e);
		}finally {
			RedisPoolManager.returnResource(jedis);
		}
    	return lo;
    }
    
}